package com.ghck.server.service.impl;

import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.ghck.server.exception.GhckException;
import com.ghck.server.exception.ErrorConstant;
import com.ghck.server.model.Pay;
import com.ghck.server.service.PayService;
import com.ghck.server.utils.AjkUtil;
import com.ghck.shop.model.OrderInfo;
import com.ghck.shop.service.OrderService;
import com.pingplusplus.exception.APIConnectionException;
import com.pingplusplus.exception.APIException;
import com.pingplusplus.exception.AuthenticationException;
import com.pingplusplus.exception.InvalidRequestException;
import com.pingplusplus.model.Charge;

@Service
@Transactional
public class PayServiceImpl implements PayService{

	@Autowired
	private OrderService orderService;
	
	private Logger logger = LoggerFactory.getLogger(PayServiceImpl.class);
	
	@Override
	public Charge generateCharge(Pay pay) {
		if(pay.getChannel() == null || pay.getChannel().trim().isEmpty()){
			throw new GhckException(ErrorConstant.PARAM_ERROR.getErrorCode(), "支付渠道不能为空");
		}
		OrderInfo  orderInfo = orderService.getOrderInfoById(pay.getOrderId());
		if(null == orderInfo){
			throw new GhckException(ErrorConstant.PARAM_ERROR.getErrorCode(), "未找到ID对应的订单");
		}
		Charge charge = null;
		Map<String, Object> chargeParams = new HashMap<String, Object>();
		chargeParams.put("order_no",  orderInfo.getOrderNo());
		chargeParams.put("amount", orderInfo.getTotalPayee());
		Map<String, String> app = new HashMap<String, String>();
		app.put("id", AjkUtil.PINGXX_APP_ID);
		chargeParams.put("app", app);
		chargeParams.put("channel",  pay.getChannel());
		chargeParams.put("currency", "cny");
		chargeParams.put("client_ip",  pay.getClientIp());
		String subject = orderInfo.getOrderTitle();
		try {
			subject = substring(subject,pay.getChannel());
		} catch (UnsupportedEncodingException e1) {
			throw new GhckException(ErrorConstant.OPERATION_ERROR.getErrorCode(),"截取商品名称出错啦");
		}
		
		chargeParams.put("subject",  subject);
		chargeParams.put("body",  subject);
		try {
			charge = Charge.create(chargeParams);
		} catch (AuthenticationException e) {
			e.printStackTrace();
			throw new GhckException(ErrorConstant.OPERATION_ERROR.getErrorCode(),e.getMessage());
		} catch (InvalidRequestException e) {
			e.printStackTrace();
			throw new GhckException(ErrorConstant.OPERATION_ERROR.getErrorCode(),e.getMessage());
		} catch (APIConnectionException e) {
			e.printStackTrace();
			throw new GhckException(ErrorConstant.OPERATION_ERROR.getErrorCode(),e.getMessage());
		} catch (APIException e) {
			e.printStackTrace();
			throw new GhckException(ErrorConstant.OPERATION_ERROR.getErrorCode(),e.getMessage());
		}
		return charge;
	}
	
	private static String substring(String orignal, String channel) throws UnsupportedEncodingException {
		// 原始字符不为null，也不是空字符串
		if (orignal != null && !"".equals(orignal)) {
			if("upacpupacp_wap".contains(channel)){
				if(charLength(orignal) >= 32){
					int len = 32;
					int num = 0;
					StringBuffer buff = new StringBuffer();
					for(int i = 0; i < len ; i++){
						char c = orignal.charAt(i);
						int charLen = isChineseChar(c);
						num+=charLen;
						if(num >= len){
							break;
						}
						buff.append(c);
					}
					return buff.toString();
					
				}else{
					return orignal;
				}
				
			}else{
				if(orignal.length() > 32){
					return orignal.substring(0,31);
				}else{
					return orignal;
				}
			}
		}
		return orignal;
	}
	
	private static int isChineseChar(char c) throws UnsupportedEncodingException {
		// 中文三个字节
		return String.valueOf(c).getBytes("UTF-8").length;
	}
	
	private static int charLength(String orignal) throws UnsupportedEncodingException{
		char c ;
		int len = 0;
		for (int i = 0; i < orignal.length(); i++) {
			c = orignal.charAt(i);
			int charLen = isChineseChar(c);
			len+=charLen;
		}
		return len;
	}
	

}
